<template>
    <el-container>
        <el-header style="text-align: center; margin: 15px 0 0 0px;">
            <el-row>
                <el-col :span="24">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item :to="{ path: '/' }">登录页</el-breadcrumb-item>
                        <el-breadcrumb-item><a href="/main/TestExamFenYe">业务管理</a></el-breadcrumb-item>
                        <el-breadcrumb-item>分页查询</el-breadcrumb-item>
                    </el-breadcrumb>
                </el-col>
            </el-row>
            <h1>登录日志增删改查</h1>
        </el-header>
        <!-- el-main 是elementUI的布局容器，用于放置页面的主要内容，
         类似的还有el-container、el-aside、el-footer、el-header -->
        <el-main style=" justify-content: center; align-items: center;">
            <el-row style="">
                <!-- 搜索表单，要与pojoTestQuery绑定 -->
                <el-form :model="pojoTestQuery" :inline="true" align="center" style="">
                    <el-form-item label="登录名" prop="name">
                        <el-input placeholder="请输入登录名" v-model="pojoTestQuery.name" autocomplete="off"
                            style="width:70%;" :clearable="true" />
                    </el-form-item>
                    <el-form-item label="登录方法" prop="charType">
                        <el-input placeholder="请输入登录方法" v-model="pojoTestQuery.charType" autocomplete="off"
                            style="width: 70%;" :clearable="true" />
                    </el-form-item>
                    <el-form-item label="登录等级" prop="doubleType">
                        <el-input placeholder="请输入登录等级" v-model="pojoTestQuery.doubleType" style="width:70%;"
                            :clearable="true" />
                    </el-form-item>
                    <el-form-item label="登录时间" prop="dateTime">
                        <el-date-picker v-model="pojoTestQuery.dateTime" type="datetime" placeholder="选择日期时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right"
                            style="width: 70%;">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch()">搜索</el-button>
                        <el-button type="info" icon="el-icon-refresh" @click="clearSelection()">重置</el-button>
                        <el-button type="success" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
                        <el-button type="success" icon="el-icon-printer"
                            @click="handleExportExcel()">前端导出excel</el-button>

                        <el-button type="success" icon="el-icon-printer"
                            @click="handleExportExcelFromBackUp()">后端导出excel</el-button>
                        <el-button type="success" icon="el-icon-upload"
                        @click="handleImportExcelFromBackUp()">后端入excel</el-button>
                        <el-tooltip class="item" effect="light" content="请选择要删除的记录！" placement="top"
                            :disabled="this.ids.length === 0 ? false : true">
                            <el-button type="danger" :disabled="this.ids.length === 0 ? true : false"
                                icon="el-icon-delete" @click="handleDelete()">批量删除</el-button>
                        </el-tooltip>
                    </el-form-item>
                </el-form>
            </el-row>
            <!-- type="selection" ref="multipleTable"是自定义的唯一标识 
        选择框 type="index" 序号 prop:每一行的属性 align="center" 居中 -->
            <el-table :data="pojoList" :model="pojoTestTable" @selection-change="handleSelectionChange" border stripe
                height="360px" style="width: 1200px; margin: 0 auto;">
                <!-- 查询列表的表格，要与pojoTestTable绑定 -->
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column type="index" label="序号" width="50px" align="center">
                </el-table-column>
                <el-table-column prop="dateTime" label="登录时间" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="name" label="登录名" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="charType" label="登录方法" width="auto" align="center">
                </el-table-column>
                <el-table-column prop="doubleType" label="登录等级" width="auto" align="center">
                </el-table-column>
                <el-table-column align="center" label="删除" width="80px" fixed="right">
                    <template slot-scope="scope"> <!-- 作用域插槽，可以获取当前行的数据 -->
                        <el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="修改" width="80px" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" @click="getById(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页，handleSizeChange是分页大小变化的事件，handleCurrentChange是当前页变化的事件 -->
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pojoTestQuery.currentIndex" :page-sizes="[5, 10, 15, 20, 50, 100]" :page-size="5"
                layout="total, sizes, prev, pager, next, jumper" :total="total" style="float: right;">
            </el-pagination>

            <!-- 新增/修改表单，打开表单:visible.sync="open" 点击表单外不关闭 :close-on-click-modal="false" -->
            <el-dialog :title="this.updateType" :visible.sync="open" :close-on-click-modal="false"
                @close="addDialogClose" width="25%">
                <el-form :model="pojoTestTable" label-width="80px" :rules="rules" ref="multipleTable">
                    <el-form-item label="登录名" prop="name">
                        <el-input placeholder="请输入登录名" v-model="pojoTestTable.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="登录方法" prop="charType">
                        <el-input placeholder="请输入登录方法" v-model="pojoTestTable.charType" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="登录等级" prop="doubleType">
                        <el-input placeholder="请输入登录等级" v-model="pojoTestTable.doubleType" :max="100"></el-input>
                    </el-form-item>
                    <el-form-item label="登录时间" prop="dateTime">
                        <el-date-picker v-model="pojoTestTable.dateTime" type="datetime" placeholder="选择日期时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right"
                            style="width: 100%;">
                        </el-date-picker>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click="open = false">取 消</el-button>
                    <el-button type="primary" @click=vaildForm(pojoTestTable)>确 定</el-button>
                </div>
            </el-dialog>
        </el-main>
        <el-footer>

        </el-footer>
    </el-container>

</template>

<script>
import * as XLSX from 'xlsx'

export default {
    name: 'TestExamFenYe',
    // props: {
    //     constVal:String  父传子组件的时候，在子组件这样接收，用this.constVal直接调用
    // },
    data() {
        return {
            open: false,           // 是否显示新增/修改表单
            updateType: "",        // 在表单左上角显示的是新增还是修改
            total: null,           // 总记录数
            pojoList: [],          // 列表数据，在执行getList()方法时赋值
            selectedRows: [], // 批量选择的行数据
            names: [],             // 批量选择的行名称
            ids: [],               // 批量选择的行id           
            dateTime: '',
            circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
            // tabel对象
            pojoTestTable: {
                id: null,
                dateTime: null,
                name: null,
                charType: null,
                doubleType: null,
            },
            // 表单对象
            pojoTestQuery: {
                id: null,
                dateTime: null,
                name: null,
                charType: null,
                doubleType: null,
                currentIndex: 1,
                pageSize: 5,
            },

            rules: {
                name: [
                    { required: true, message: '请输入日志名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                charType: [
                    { required: true, message: '请输入登录方法', trigger: 'blur' },
                ],
                dateTime: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                doubleType: [
                    { required: true, message: '请输入登录等级', trigger: 'blur' }
                ],
            }

        };
    },
    mounted: function () {    // 页面加载完成后执行
        this.getList();
        // console.log("----分页里面，query传值-----",this.$route.query) 接收路由传值，现在不需要
    },
    methods: {
        // handle 处理提示消息
        handleUpdate(pojoTestTable) {
            this.$confirm('修改名称为：' + pojoTestTable.name + '的记录?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.update(pojoTestTable);
                this.open = false;
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消修改' });
            });
        },

        handleInsert(pojoTestTable) {
            this.$confirm('新增名称为：' + pojoTestTable.name + '的记录?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.insert(pojoTestTable);
                this.open = false;
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消新增' });
            });
        },

        handleDelete(row) {
            // const ids = row.id || this.ids
            // const names = row.name || this.names
            var ids = null;
            var names = null;
            if (row != null) {
                console.log("row不为空！row = ", row);
                ids = row.id
                names = row.name
            } else {
                console.log("ids = ", this.ids);
                ids = this.ids
                names = this.names
            }

            // 删除登录日志(集成批量删除)
            this.$confirm('此操作将永久删除记录名为：' + names + '，是否继续?', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delete(ids);
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消删除' });
            });
        },

        handleAdd() {
            this.pojoTestTable = {}
            this.updateType = "新增";
            this.open = true;
        },

        handleSearch() {
            this.getList();
        },

        /**
         * 后端导出excel
         */
        handleExportExcelFromBackUp() {
            this.$confirm('此操作将导出当前页所有数据，是否继续?', '导出提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get("http://localhost:8082/pojoTest/exportEquipmentExcel", {
                responseType: 'blob',   // 重要：告诉axios预期服务器返回的数据类型
            })
                .then(res => {
                    const blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel",
                    });
                    // 获取 文件名
                    var fileName = decodeURIComponent("学生信息.xls");
                    //创建一个 a 标签
                    const link = document.createElement("a");
                    //不显示a标签
                    link.style.display = "none";
                    // 给a 标签的href属性赋值
                    link.href = URL.createObjectURL(blob);
                    link.setAttribute("download", fileName);
                    //把a标签插入页面中
                    document.body.appendChild(link);
                    link.click();
                    //点击之后移除a标签
                    document.body.removeChild(link);
                }).catch(error => {
                    //请求失败，触发catch中的函数 可省略
                    console.log(error)
                    console.log("请求失败...");
                })

            }).catch(() => {
                this.$message({ type: 'info', message: '已取消导出' });
            });
        },

        /**
         * 前端导出excel
         */
        handleExportExcel() {
            this.$confirm('此操作将导出当前页所有数据，是否继续?', '导出提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                try {
                    // 创建工作簿
                    const wb = XLSX.utils.book_new();

                    // 准备导出数据 - 注意这里应该使用 this.pojoList 而不是 this.pojoTestTable
                    const exportData = this.pojoList.map(item => ({
                        'ID': item.id,
                        '登录名': item.name,
                        '登录时间': item.dateTime,
                        '登录方法': item.charType,
                        '登录等级': item.doubleType,
                    }));

                    // 将数据转换为工作表
                    const ws = XLSX.utils.json_to_sheet(exportData);

                    // 将工作表添加到工作簿
                    XLSX.utils.book_append_sheet(wb, ws, '登录日志数据');

                    // 生成Excel文件并下载
                    const fileName = `登录日志_${new Date().toLocaleString().replace(/[/:\\]/g, '-')}.xlsx`;
                    XLSX.writeFile(wb, fileName);

                    // 显示成功通知
                    this.$message({
                        message: '导出成功',
                        type: 'success'
                    });
                } catch (error) {
                    console.error('导出失败:', error);
                    this.$message.error('导出失败，请查看控制台详情');
                }
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消导出' });
            });
        },

        /**
         * 后端导入excel
         */
        handleImportExcelFromBackUp() {
            this.$confirm('此操作将导入excel数据，是否继续?', '导入提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post("http://localhost:8082/pojoTest/importEquipmentExcel")
                   .then(response => {
                        console.log(response);
                        this.$message({
                            message: '导入成功',
                            type: 'success'
                        });
                        this.getList();
                    }).catch(error => {
                        console.log(error);
                        this.$message.error('导入失败，请查看控制台详情');
                    })
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消导入' });
            });
        },

        // 具体的业务处理
        getList() {
            // 获取登录日志
            console.log("查询的对象：", this.pojoTestQuery);
            this.$axios.get('http://127.0.0.1:8082/pojoTest/fenYeList', { params: this.pojoTestQuery })
                .then(response => {
                    console.log("后台返回的对象", response.data.data);
                    this.pojoList = response.data.data.pojoTestList
                    this.total = response.data.data.totalCount

                }).catch(error => {
                    console.log("query failed" + error);
                });
        },


        delete(loginLogIds) {
            console.log("删除的对象：", loginLogIds);
            this.$axios.delete('http://127.0.0.1:8082/pojoTest/deleteBatch/' + loginLogIds)
                .then(response => {
                    if (response.data.data > 0) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        });
                    }
                    this.getList();
                }).catch(error => {
                    console.log("delete failed" + error);
                });
        },

        getById(id) {
            this.open = true;
            this.updateType = "修改";
            // 获取登录日志
            this.$axios.get('http://127.0.0.1:8082/pojoTest/getById/' + id)
                .then(response => {
                    this.pojoTestTable = {};
                    this.pojoTestTable = response.data.data;
                    this.open = true;
                }).catch(error => {
                    console.log("query failed" + error);
                });
        },

        update(pojoTestTable) {
            console.log("更新的对象：", pojoTestTable);
            const copyPojo = JSON.parse(JSON.stringify(pojoTestTable));
            // 修改登录日志 因为要传对象，用逗号，所以最后update路径不写 /
            this.$axios.put('http://127.0.0.1:8082/pojoTest/update', copyPojo)
                .then(response => {
                    console.log(response);
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.getList();
                }).catch(error => {
                    console.log("update failed" + error);
                });
        },

        insert(pojoTestTable) {
            const copyPojo = JSON.parse(JSON.stringify(pojoTestTable));
            console.log("新增的对象：", copyPojo);
            // 新增登录日志 最后insert路径不写 /
            this.$axios.post('http://127.0.0.1:8082/pojoTest/add', copyPojo)
                .then(response => {
                    console.log(response);
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    });
                    this.open = false;
                    this.getList();
                }).catch(error => {
                    console.log("insert failed" + error);
                });
        },


        // 表格相关

        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pojoTestQuery.pageSize = val;
            this.getList();

        },

        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pojoTestQuery.currentIndex = val;
            this.getList();
        },

        /**
         * 验证表单
         * @param pojoTestTable 登录日志对象 
         */
        vaildForm(pojoTestTable) {
            // 表单验证
            this.$refs.multipleTable.validate((valid) => {
                if (valid) {
                    this.submitForm(pojoTestTable);
                } else {
                    alert('请检查输入项');
                    return false;
                }
            });
        },

        /**
         * 提交表单
         * @param pojoTestTable 登录日志对象
         */
        submitForm(pojoTestTable) {
            // 新增或修改登录日志   
            if (this.pojoTestTable.id) {
                // 有主键修改登录日志
                this.updateType = "修改";
                this.handleUpdate(pojoTestTable);
            } else {
                // 没有主键就新增
                this.updateType = "新增";
                this.handleInsert(pojoTestTable);
                this.getList();
            }
        },



        /**
         * 清空选择
         * @param {Object} rows 行数据
         */
        clearSelection() {
            this.pojoTestQuery = {
                id: null,
                dateTime: null,
                name: null,
                charType: null,
                doubleType: null,
                pageSize: this.pojoTestQuery.pageSize,
                currentIndex: this.pojoTestQuery.currentIndex,
            };
            this.getList();
        },

        addDialogClose() {
            this.$refs['multipleTable'].resetFields();
        },

        /**
         * 选择行对象
         * @param rows 行数据
         */
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);

                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.names = selection.map(item => item.name);
            console.log(this.ids);
            console.log(this.names);
        },



    },
};
</script>
<style scoped></style>